package cn.agriculture.web.controller;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.agriculture.web.form.AlipayForm;
import cn.agriculture.web.form.CartForm;
import cn.agriculture.web.form.GoodsForm;
import cn.agriculture.web.form.UVO;
import cn.agriculture.web.service.CartService;
import cn.agriculture.web.service.GoodsService;

@Slf4j
@Controller("CartController")
@RequestMapping("/")
@PropertySource("classpath:system.properties")
public class CartController {
	
	@Autowired
	CartService cartService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	private Environment env;
	
	@RequestMapping(value = "initCart", method = RequestMethod.GET)
    public String initCart(Model model, HttpSession session, Device device) throws SQLException {
    	log.info("购物车初始化");
    	UVO uvo = (UVO)session.getAttribute("UVO");
    	if (uvo == null || StringUtils.isEmpty(uvo.getGuestId())) {
    		return "redirect:/initGuestLogin";
    	}
    	CartForm cartForm = new CartForm();
    	cartForm.setGuestId(uvo.getGuestId());
    	model.addAttribute("cartList", cartService.searchCartList(cartForm));
    	model.addAttribute("list", cartService.searchAlipayHistoryList(cartForm));
    	if(device.isNormal()) {
    		return "shop/cart/cartList";
    	} else {
    		return "mobile/cart/cartList";
    	}
    }
	
    @RequestMapping(value = "addCart", method = RequestMethod.POST)
    public String executeAddCart(Model model, HttpSession session, CartForm cartForm, Device device) throws SQLException {
    	log.info("追加购物车");
    	UVO uvo = (UVO)session.getAttribute("UVO");
    	
    	if (uvo == null || StringUtils.isEmpty(uvo.getGuestId()) || uvo.getGuestId().length() > 4) {
    		if (uvo == null || StringUtils.isEmpty(uvo.getGuestId()) || "Guest".equals(uvo.getGuestId().substring(0, 5))) {
    			uvo = new UVO();
    			Date date = new Date();
        		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        		uvo.setUserId("Guest" + dateformat.format(date));
        		uvo.setGuestId("Guest" + dateformat.format(date));
        		uvo.setUserName("来宾" + dateformat.format(date));
        		log.info("匿名购买商品销售页面初始化。");
        		AlipayForm alipayForm = new AlipayForm();
        		cartForm.setGuestId(uvo.getGuestId());
        		alipayForm = cartService.searchAlipay(cartForm);
        		if (alipayForm == null) {
        			GoodsForm goodsForm = new GoodsForm();
        			goodsForm.setCommodityId(cartForm.getCommodityId());
        			model.addAttribute("goodsForm", goodsService.searchGoods(goodsForm));
        			model.addAttribute("message", "库存不够！");
        			if(device.isNormal()) {
        	    		return "shop/goods/goodsDetail";
        	    	} else {
        	    		return "mobile/goods/goodsDetail";
        	    	}
        		}
        		model.addAttribute("alipayForm", alipayForm);
        		if(device.isNormal()) {
        			return "shop/alipay/guestAlipayConfirm";
        		} else {
        			return "mobile/alipay/guestAlipayConfirm";
        		}
    		}
    	}
    	cartForm.setUpdateUser(uvo.getGuestName());
		Date date = new Date();
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cartForm.setUpdateTime(dateformat.format(date));
		cartForm.setGuestId(uvo.getGuestId());
		AlipayForm alipayForm = new AlipayForm();
		alipayForm = cartService.searchAlipay(cartForm);
		if (alipayForm == null) {
			GoodsForm goodsForm = new GoodsForm();
			goodsForm.setCommodityId(cartForm.getCommodityId());
			model.addAttribute("goodsForm", goodsService.searchGoods(goodsForm));
			model.addAttribute("message", "库存不够！");
			if(device.isNormal()) {
	    		return "shop/goods/goodsDetail";
	    	} else {
	    		return "mobile/goods/goodsDetail";
	    	}
		}
		
    	boolean result = cartService.addCart(cartForm);
    	if (!result) {
    		throw new SQLException("追加购物车失败！");
    	}
    	model.addAttribute("cartList", cartService.searchCartList(cartForm));
    	model.addAttribute("list", cartService.searchAlipayHistoryList(cartForm));
    	if(device.isNormal()) {
    		return "shop/cart/cartList";
    	} else {
    		return "mobile/cart/cartList";
    	}
    }
    
    @RequestMapping(value = "delCart", method = RequestMethod.GET)
    public String executeDelCart(Model model, HttpSession session, CartForm cartForm, Device device) throws SQLException {
    	log.info("删除购物车");
    	UVO uvo = (UVO)session.getAttribute("UVO");
    	if (uvo == null || StringUtils.isEmpty(uvo.getGuestId())) {
    		return "redirect:/initGuestLogin";
    	}
    	cartForm.setUpdateUser(uvo.getGuestName());
		Date date = new Date();
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cartForm.setUpdateTime(dateformat.format(date));
    	boolean result = cartService.delCart(cartForm);
    	if (!result) {
    		throw new SQLException("删除购物车失败！");
    	}
    	cartForm.setGuestId(uvo.getGuestId());
    	model.addAttribute("cartList", cartService.searchCartList(cartForm));
    	model.addAttribute("list", cartService.searchAlipayHistoryList(cartForm));
        if(device.isNormal()) {
    		return "shop/cart/cartList";
    	} else {
    		return "mobile/cart/cartList";
    	}
    }
    
    @RequestMapping(value = "alipayConfirm", method = RequestMethod.POST)
    public String alipayConfirm(Model model, HttpSession session, Device device) {
    	log.info("确认支付");
    	CartForm cartForm = new CartForm();
    	UVO uvo = (UVO)session.getAttribute("UVO");
    	if (uvo == null || StringUtils.isEmpty(uvo.getGuestId())) {
    		return "redirect:/initGuestLogin";
    	}
    	cartForm.setGuestId(uvo.getGuestId());
    	List<CartForm> list = cartService.searchCartList(cartForm);
    	AlipayForm alipayForm = new AlipayForm();
    	String body = "您购买的商品如下：";
    	Double price = 0d;
    	for (CartForm item : list) {
    		body = body + "品名：" + item.getCommodityName() +", 数量："+ item.getCount() +", 总价："+ String.valueOf(Double.valueOf(item.getCount())*Double.valueOf(item.getRetailPrice())) +";";
    		price = price + Double.valueOf(item.getCount())*Double.valueOf(item.getRetailPrice());
    	}
    	alipayForm.setBody(body);
    	alipayForm.setOutTradeNo(list.get(0).getCartId());
    	// 不满88元加8元邮费
    	if(price < 88) {
    		price = price + 8;
    		body = body + "(由于本次订单未满88元，加收您邮费8元)";
    	}
    	alipayForm.setPrice(price.toString());
    	alipayForm.setReceiveAddress(uvo.getAddress());
    	alipayForm.setReceiveMobile(uvo.getMobile());
    	alipayForm.setReceiveName(uvo.getGuestName());
    	alipayForm.setReceivePhone(uvo.getPhone());
    	alipayForm.setReceiveZip(uvo.getZip());
    	String host = env.getProperty("host.web");
    	alipayForm.setShowUrl(host + "/initCart");
    	alipayForm.setSubject(body);
    	model.addAttribute("alipayForm", alipayForm);
    	cartForm.setGuestId(uvo.getGuestId());
    	model.addAttribute("cartList", cartService.searchCartList(cartForm));
        if(device.isNormal()) {
    		return "shop/alipay/alipayConfirm";
    	} else {
    		return "mobile/alipay/alipayConfirm";
    	}
    }
    
    @RequestMapping(value = "replayAlipay", method = RequestMethod.GET)
    public String replayAlipay(Model model, AlipayForm alipayForm, HttpSession session, Device device) {
    	log.info("重新支付");
    	AlipayForm result = cartService.searchAlipayHistory(alipayForm);
    	alipayForm.setBody(result.getBody());
    	alipayForm.setOutTradeNo(result.getOutTradeNo());
    	alipayForm.setPrice(result.getPrice());
    	alipayForm.setReceiveAddress(result.getReceiveAddress());
    	alipayForm.setReceiveMobile(result.getReceiveMobile());
    	alipayForm.setReceiveName(result.getReceiveName());
    	alipayForm.setReceivePhone(result.getReceivePhone());
    	alipayForm.setReceiveZip(result.getReceiveZip());
    	alipayForm.setShowUrl(result.getShowUrl());
    	alipayForm.setSubject(result.getSubject());
    	model.addAttribute("alipayForm", alipayForm);
    	CartForm cartForm = new CartForm();
    	UVO uvo = (UVO)session.getAttribute("UVO");
    	if (uvo == null || StringUtils.isEmpty(uvo.getGuestId())) {
    		return "redirect:/initGuestLogin";
    	}
    	cartForm.setGuestId(uvo.getGuestId());
    	model.addAttribute("cartList", cartService.searchCartList(cartForm));
        if(device.isNormal()) {
    		return "shop/alipay/replayAlipayConfirm";
    	} else {
    		return "mobile/alipay/replayAlipayConfirm";
    	}
    }
}
